<template>
  <view class="container" :style="appThemeStyle">
    <!-- 搜索头部 - 固定在顶部 -->
    <view class="search-header-fixed">
      <view class="search-wrapper">
        <view class="search-input">
          <view class="search-input-wrapper">
            <view class="left">
              <text class="search-icon icon iconfont icon-sousuo"></text>
            </view>
            <view class="right">
              <input v-model="searchValue" class="input" placeholder="请输入企业名称" type="text"
                @input="onSearchInput" @confirm="onSearch" />
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 列表内容 -->
    <mescroll-body ref="mescrollRef" :sticky="true" @init="mescrollInit" :down="{ use: false }" :up="upOption"
      :bottombar="false" @up="upCallback">
      
      <!-- 排行榜区域 - 跟随滚动 -->
      <view class="ranking-section">
        <view class="image-ranking-section">
          <!-- 左侧图片占位 -->
          <view class="left-image-placeholder">
            <view class="trending-badge">
              <text class="badge-month">Jul | 2025</text>
              <text class="badge-title">优质企业榜单</text>
              <text class="badge-subtitle">探索卓越企业</text>
            </view>
          </view>
          <!-- 右侧排行榜 -->
          <view class="right-rankings">
            <view class="ranking-item" v-for="(item, index) in trendingData" :key="index">
              <view class="rank-number" :class="getRankClass(index)">{{ index + 1 }}</view>
              <view class="rank-icon">
                <span :class="getIconClass(index)"></span>
              </view>
              <view class="rank-info">
                <text class="rank-name">{{ item.name }}</text>
                <text class="rank-count">{{ item.count }}</text>
              </view>
              <view class="trend-icon" :class="item.trend">
                <span v-if="item.trend === 'up'" class="icon iconfont icon-shangjiantou"></span>
                <span v-else class="icon iconfont icon-changfangxing"></span>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 分类和筛选区域容器 -->
      <view class="categories-filters-container">
        <!-- 热门分类标签区域 -->
        <view class="hot-categories-section">
          <scroll-view class="categories-scroll" scroll-x="true" show-scrollbar="false">
            <view class="categories-list">
              <view class="category-tag" :class="{ 'active': selectedCategory === category.value }"
                v-for="category in categoryOptions" :key="category.value"
                @click="selectCategory(category.value)">
                <text class="category-icon" v-if="category.icon">{{ category.icon }}</text>
                <text class="category-text">{{ category.name }}</text>
              </view>
            </view>
          </scroll-view>
        </view>
        <!-- 地区和时间筛选 -->
        <view class="filters-section">
          <!-- 地区筛选 -->
          <picker class="location-filter" :value="selectedRegionIndex" :range="regionOptions" range-key="name"
            @change="onRegionChange">
            <view class="filter-button location-btn">
              <text class="filter-text">{{ regionOptions[selectedRegionIndex]?.name || '北京市' }}</text>
              <text class="filter-arrow">▼</text>
            </view>
          </picker>
          <!-- 时间筛选 -->
          <picker class="time-filter" mode="date" :value="selectedDate" @change="onDateChange">
            <view class="filter-button time-btn">
              <text class="filter-text">{{ selectedDate || '时间' }}</text>
              <text class="filter-arrow">▼</text>
            </view>
          </picker>
        </view>
      </view>
      
      <view class="list-content">
        <!-- 企业列表 -->
        <view class="company-list">
          <view class="company-card" v-for="(item, index) in goodsList.data" :key="index"
            @click="onTargetCompany(item)">
            <!-- 企业名称 -->
            <view class="company-title">
              <text class="title-text">{{ item.goods_name || item.company_name || item.name }}</text>
            </view>
            <!-- 用户信息 -->
            <view class="user-info">
              <text class="user-name gradient-text-green-red">用户</text>
              <text class="user-text">{{item.enterprise_status_text}}</text>
            </view>
            <!-- 图片预览区域 -->
            <view class="image-gallery">
              <view class="image-item" :class="getImageItemClass(i)" v-for="i in 3" :key="i">
                <image class="preview-image" :src="item.goods_image || `/placeholder.svg?height=180&width=120`"
                  mode="aspectFill" />
              </view>
            </view>
            <!-- 底部操作区 -->
            <view class="bottom-actions">
              <!-- 左侧资质标签 -->
              <view class="qualification-tags">
                <text class="mini-tag" :class="getQualificationTagClass(qualification)"
                  v-for="(qualification, qIndex) in parseQualificationStatus(item.qualification_status)"
                  :key="qIndex">
                  {{ qualification }}
                </text>
                <!-- 如果没有资质信息，显示默认标签 -->
                <text class="mini-tag tag-default" v-if="!item.qualification_status">
                  法人服务
                </text>
              </view>
              <!-- 右侧联系按钮 -->
              <view class="contact-button" @click.stop="onContact(item)">
                <text class="contact-text">联系</text>
              </view>
            </view>
          </view>
        </view>
        <!-- 空状态 -->
        <view v-if="goodsList.data.length === 0 && !loading" class="empty-state">
          <view class="empty-icon">📋</view>
          <text class="empty-text">{{ searchValue ? `暂无"${searchValue}"相关企业信息` : '暂无企业信息' }}</text>
        </view>
      </view>
    </mescroll-body>
  </view>
</template>

<script>
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
import {
  getEmptyPaginateObj,
  getMoreListData
} from '@/core/app'
import * as GoodsApi from '@/api/goods'

const pageSize = 15

export default {
  mixins: [MescrollMixin],
  props: {
    list: {
      type: Array,
      default: []
    },
    setting: {
      type: Object,
      default: () => {}
    },
  },
  data() {
    return {
      // 搜索关键词
      searchValue: '',
      // 搜索防抖定时器
      searchTimer: null,
      // 企业列表
      goodsList: getEmptyPaginateObj(),
      // 加载状态
      loading: false,
      // 筛选条件
      selectedCategory: 'all',
      selectedRegionIndex: 0,
      selectedDate: '',
      // 热门排行数据
      trendingData: [{
          name: '北京森哲科技有限公司',
          count: '200',
          icon: '📷',
          trend: 'up'
        },
        {
          name: '北京撒码科技游戏公司',
          count: '167',
          icon: '🎯',
          trend: 'up'
        },
        {
          name: '星辰科技有限公司',
          count: '49',
          icon: '🐕',
          trend: 'ping'
        }
      ],
      // 分类选项
      categoryOptions: [{
          value: 'all',
          name: '全部',
          icon: ''
        },
        {
          value: '10',
          name: '纳税等级A',
          icon: ''
        },
        {
          value: '20',
          name: '纳税等级B',
          icon: ''
        },
        {
          value: '30',
          name: '纳税等级C',
          icon: ''
        },
        {
          value: '40',
          name: '纳税等级D',
          icon: ''
        },
      ],
      // 地区选项
      regionOptions: [{
          value: '',
          name: '北京市'
        },
        {
          value: 'shanghai',
          name: '上海市'
        },
        {
          value: 'guangzhou',
          name: '广州市'
        },
        {
          value: 'shenzhen',
          name: '深圳市'
        },
        {
          value: 'hangzhou',
          name: '杭州市'
        }
      ],
      // 上拉加载配置
      upOption: {
        auto: true,
        page: {
          size: pageSize
        },
        noMoreSize: 3,
        toTop: {
          right: 30,
          bottom: 48,
          zIndex: 9
        }
      }
    }
  },
  methods: {
    /**
     * 获取排名样式类
     */
    getRankClass(index) {
      if (index === 0) return 'rank-first'
      if (index === 1) return 'rank-second'  
      if (index === 2) return 'rank-third'
      return ''
    },
    
    /**
     * 分类选择
     */
    selectCategory(categoryValue) {
      this.selectedCategory = categoryValue
      this.onRefreshList()
    },
    /**
     * 地区筛选变化
     */
    onRegionChange(e) {
      this.selectedRegionIndex = e.detail.value
      this.onRefreshList()
    },
    /**
     * 日期筛选变化
     */
    onDateChange(e) {
      this.selectedDate = e.detail.value
      this.onRefreshList()
    },
    /**
     * 上拉加载的回调
     */
    upCallback(page) {
      const app = this
      app.getGoodsList(page.num)
        .then(list => {
          const curPageLen = list.data.length
          const totalSize = list.data.total
          app.mescroll.endBySize(curPageLen, totalSize)
        })
        .catch(() => app.mescroll.endErr())
    },
    /**
     * 获取企业列表
     */
    getGoodsList(pageNo = 1) {
      const app = this
      return new Promise((resolve, reject) => {
        const param = {
          sortType: 'all',
          sortPrice: 0,
          categoryId: 0,
          goodsName: app.searchValue || '',
          tax_brackets: app.selectedCategory,
          region: app.regionOptions[app.selectedRegionIndex]?.value || '',
          date: app.selectedDate || '',
          page: pageNo,
          filters: [],
          onlyInStock: false
        }
        GoodsApi.list(param)
          .then(result => {
            const newList = result.data.list
            app.goodsList.data = getMoreListData(newList, app.goodsList, pageNo)
            app.goodsList.last_page = newList.last_page
            resolve(newList)
          })
          .catch(reject)
      })
    },
    /**
     * 搜索输入事件
     */
    onSearchInput(e) {
      const app = this
      const value = e.detail.value || e.target.value
      app.searchValue = value
      if (app.searchTimer) {
        clearTimeout(app.searchTimer)
      }
      app.searchTimer = setTimeout(() => {
        app.onRefreshList()
      }, 500)
    },
    /**
     * 执行搜索
     */
    onSearch() {
      this.onRefreshList()
    },
    /**
     * 刷新列表数据
     */
    onRefreshList() {
      this.goodsList = getEmptyPaginateObj()
      setTimeout(() => {
        if (this.mescroll) {
          this.mescroll.resetUpScroll()
        }
      }, 120)
    },
	
	// 根据索引获取对应的图标类名
	  getIconClass(index) {
	    const iconClasses = [
	      'icon iconfont icon-qiyezizhi',    // 第一个图标
	      'icon iconfont icon-qiye2',       // 第二个图标
	      'icon iconfont icon-qiyefuwu'     // 第三个图标
	    ];
	    return iconClasses[index] || 'icon iconfont icon-qiyezizhi'; // 默认使用第一个图标
	  },
	  
    /**
     * 点击企业项
     */
    onTargetCompany(item) {
      console.log('点击企业:', item)
      const goodsId = item.goods_id || item.company_id || item.id
      this.$navTo('pages/goods/detail', {
        goodsId
      })
    },
	
	    getImageItemClass(index) {
	      if (index === 1) return 'image-first'
	      if (index === 2) return 'image-middle'  
	      if (index === 3) return 'image-last'
	      return ''
	    },
    /**
     * 联系按钮点击事件
     */
    onContact(item) {
      uni.navigateTo({
        url: '/pages/goods/components/ReviewPopup?goodsId=' + item.goods_id,
      })
    },
    /**
     * 获取当前时间
     */
    getCurrentTime() {
      const now = new Date()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      return `${month}.${day} ${hours}:${minutes}`
    },
    /**
     * 解析资质状态
     */
    parseQualificationStatus(qualificationStatus) {
      if (!qualificationStatus) return []
      return qualificationStatus.split(',')
        .map(status => status.trim())
        .filter(status => status)
        .slice(0, 3)
    },
    /**
     * 获取资质标签样式
     */
    getQualificationTagClass(qualification) {
      const classMap = {
        'ISO9001': 'tag-orange',
        '高新技术企业': 'tag-green',
        '涉密资质': 'tag-blue'
      }
      return classMap[qualification] || 'tag-default'
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background: #f2f4f3;
  min-height: 100vh;
}

// 固定搜索头部
.search-header-fixed {
  position: fixed;
  top: var(--window-top);
  left: 0;
  right: 0;
  z-index: 100;
  background: #c8f0d8; // 浅绿色背景
  padding: 16rpx 20rpx 14rpx 20rpx;
}

.search-wrapper {
  display: flex;
  height: 72rpx;
}

.search-input {
  flex: 1;
  background: #fff;
  border-radius: 36rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.search-input-wrapper {
  display: flex;
  background: #fff;
  border-radius: 36rpx;
  padding: 0 10rpx;
  
  .left {
    display: flex;
    width: 60rpx;
    justify-content: center;
    align-items: center;
    
    .search-icon {
      color: #000;
      font-size: 40rpx;
    }
  }
  
  .right {
    flex: 1;
    
    .input {
      font-size: 28rpx;
      height: 72rpx;
      display: flex;
      align-items: center;
      width: 100%;
      padding: 0 20rpx 0 0;
      border: none;
      outline: none;
      background: transparent;
      color: #333;
      
      &::placeholder {
        color: #ccc;
      }
    }
  }
}

// 排行榜区域 - 跟随滚动
.ranking-section {
  margin-top: 100rpx; // 为固定搜索框留出空间
  background: #c8f0d8;
  padding: 15rpx;
}

// 图片和排行区域
.image-ranking-section {
  display: flex;
  padding: 24rpx;
  background: #f0f9f3; // 更浅的绿色背景
  border-radius: 25rpx; // 添加圆角
  gap: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.left-image-placeholder {
  width: 320rpx;
  height: 200rpx;
  border-radius: 16rpx;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  padding: 24rpx;
}

.trending-badge {
  color: #fff;
  width: 100%;
}

.badge-month {
  font-size: 24rpx;
  font-weight: 600;
  margin-bottom: 8rpx;
  display: block;
  opacity: 0.9;
  background: #00d4aa;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  width: fit-content;
  color: #000;
  font-weight: bold;
}

.badge-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
  display: block;
  line-height: 1.2;
  background: linear-gradient(90deg, #00d4aa 0%, #26de81 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.badge-subtitle {
  font-size: 22rpx;
  opacity: 0.8;
  display: block;
  letter-spacing: 2rpx;
  margin-top: 4rpx;
  color: #000;
}

.right-rankings {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  justify-content: space-around;
  max-width: 350rpx;
}

// 排行榜项目
.ranking-item {
  display: flex;
  align-items: center;
  padding: 8rpx 0;
  border-radius: 12rpx;
  height: 50rpx;
}

.rank-number {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22rpx;
  font-weight: bold;
  margin-right: 12rpx;
  flex-shrink: 0;
  color: #000;
}

.rank-icon {
  font-size: 28rpx;
  width: 36rpx;
  text-align: center;
  margin-right: 12rpx;
  flex-shrink: 0;
}

.rank-info {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-width: 0;
  margin-right: 12rpx;
}

.rank-name {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex-shrink: 1;
  max-width: 200rpx;
}

.rank-count {
  font-size: 20rpx;
  color: #999;
  white-space: nowrap;
  margin-left: 12rpx;
  flex-shrink: 0;
}

.trend-icon {
  font-size: 24rpx;
  width: 32rpx;
  text-align: center;
  flex-shrink: 0;
  
  &.up {
    color: #00b894;
  }
  
  &.ping {
    color: #00b894;
  }
  
  &.down {
    color: #e17055;
  }
}

// 分类和筛选区域容器
.categories-filters-container {
  background: #fff;
  margin-top: 0; // 移除原来的margin-top
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  border-radius: 30rpx;
}

// 其余样式保持不变...
// 热门分类标签区域
.hot-categories-section {
  background: #fff;
  padding: 20rpx 24rpx 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  border-radius: 30rpx;
}

.categories-scroll {
  white-space: nowrap;
  width: 100%;
}

.categories-list {
  display: inline-flex;
  gap: 20rpx;
  width: max-content;
}

.category-tag {
  display: inline-flex;
  align-items: center;
  gap: 6rpx;
  padding: 6rpx 0;
  margin-left: 10px;
  white-space: nowrap;
  font-size: 25rpx;
  color: #9b9b9b;
  flex-shrink: 0;
  
  &.active {
    background: linear-gradient(to bottom, #fff 60%, #75fb8f 50%);
    color: #000;
    font-size: 30rpx;
    font-weight: bold;
  }
}

.category-icon {
  font-size: 24rpx;
}

.category-text {
  font-size: 30rpx;
  white-space: nowrap;
}

// 筛选区域
.filters-section {
  display: flex;
  gap: 20rpx;
  padding: 20rpx 24rpx 20rpx 20rpx;
  background: #fff;
}

.filter-button {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  background: #fafafa;
  color: #333;
}

.filter-text {
  font-size: 28rpx;
  font-weight: 500;
}

.filter-arrow {
  font-size: 18rpx;
  margin-left: 8rpx;
}

// 列表内容
.list-content {
  background: #f2f4f3;
  min-height: 100vh;
  padding: 25rpx;
}

// 企业列表
.company-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

// 企业卡片
.company-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx 24rpx 24rpx 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  
  &:active {
    transform: scale(0.98);
    transition: transform 0.1s ease;
  }
}

// 企业标题
.company-title {
  margin-bottom: 16rpx;
}

.title-text {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
  line-height: 1.4;
}

// 用户信息
.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  gap: 12rpx;
  flex-wrap: wrap;
}

.user-name {
  font-size: 24rpx;
  font-weight: 600;
}

.user-text {
  color: #55b590;
  font-size: 22rpx;
}

.gradient-text-green-red {
  background: linear-gradient(90deg, #00d4aa 0%, #26de81 25%, #fed330 75%, #f39c12 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

// 图片画廊
.image-gallery {
  display: flex;
  gap: 4rpx;
  margin-bottom: 20rpx;
}

.image-item {
  flex: 1;
  height: 180rpx;
  overflow: hidden;
  background: #f5f7fa;
  
  // 第一张图片：左上角和左下角有圆角
  &.image-first {
    border-radius: 12rpx 0 0 12rpx;
  }
  
  // 第二张图片：四个角都没有圆角
  &.image-middle {
    border-radius: 0;
  }
  
  // 第三张图片：右上角和右下角有圆角
  &.image-last {
    border-radius: 0 12rpx 12rpx 0;
  }
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

// 底部操作区
.bottom-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.qualification-tags {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.mini-tag {
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  color: #fff;
  
  &.tag-orange {
    background-color: #ff9f43;
  }
  
  &.tag-green {
    background-color: #1dd1a1;
  }
  
  &.tag-blue {
    background-color: #3498db;
  }
  
  &.tag-default {
    background-color: #95a5a6;
  }
}

.contact-button {
  background: #2c2c2c;
  padding: 10rpx 40rpx;
  border-radius: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
  
  &:active {
    background: #1a1a1a;
    transform: scale(0.95);
  }
}

.contact-text {
  color: #77f99b;
  font-size: 26rpx;
  font-weight: 600;
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 120rpx 0;
  gap: 24rpx;
}

.empty-icon {
  font-size: 80rpx;
  opacity: 0.4;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  text-align: center;
}

.icon-changfangxing {
  font-size: 13px;
}
</style>
